﻿using MvcWechat.Common;
using MvcWechat.Cryptography;
using MvcWechat.Models;
using MvcWechat.ServiceReference1;
using MvcWechat.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Threading.Tasks;
using System.Web.Configuration;
using System.Web.Mvc;

namespace MvcWechat.Controllers
{
    public class ServiceController : BaseController
    {
        Dictionary<string, object> tmpAllResult = new Dictionary<string, object>();
        // GET: /Service/
        //
        // GET: /Service/
        private static RetailClient  service = new RetailClient();
        /// <summary>
        /// 在线库存
        /// </summary>
        /// <returns></returns>
        public JsonResult GetInventoryInfos()
        {
            string inventoryJson = GetParentKeyInputJson();
            try
            {
                return Json(service.GetInventoryInfos(inventoryJson,""));
            }
            catch (Exception ex)
            {
                return Json("程序内部错误，请调试程序。" + ex.Message);
            }
        }
        /// <summary>
        /// 在线库存
        /// </summary>
        /// <returns></returns>
        public JsonResult GetInventoryInfo()
        {
            string inventoryJson = GetParentKeyInputJson();
            try
            {
                return Json(service.GetInventoryInfos(inventoryJson,""));
            }
            catch (Exception ex)
            {
                return Json("程序内部错误，请调试程序。" + ex.Message);
            }
        }
        /// <summary>
        /// 在线库存总数
        /// </summary>
        /// <returns></returns>
        public JsonResult GetInventoryInfosCount()
        {
            string inventoryJson = GetInputJson();
            try
            {
                return Json(service.GetInventoryInfosCount(inventoryJson));
                // return Json(1);
            }
            catch (Exception ex)
            {
                return Json("程序内部错误，请调试程序。" + ex.Message);
            }
        }
        /// <summary>
        /// 我的订单
        /// </summary>
        /// <returns></returns>
        public JsonResult GetOrders()
        {
            string ordersJson = GetInputJson();
            return Json(service.GetOrders(ordersJson));
        }
        /// <summary>
        /// 购物车列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetCartInfos()
        {
            string cartsJson = GetInputJson();
            return Json(service.GetCartInfos(cartsJson));
        }
        /// <summary>
        /// 客户删除购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult DeleteAllCart()
        {
            string customerRegisterJson = GetInputJson();
            return Json(service.DeleteCart(customerRegisterJson));
        }
        /// <summary>
        /// 加入购物车(仅单个)
        /// </summary>
        /// <returns></returns>
        public JsonResult AddToCart()
        {
            string addToCartJson = GetInputJson();
            return Json(service.AddCart(addToCartJson));
        }
        /// <summary>
        /// 加入购物车(多个和单个)
        /// </summary>
        /// <returns></returns>
        public JsonResult MultiAddToCart()
        {
            string mulitAddToCartJson = GetInputJson();
            return Json(service.AddCart(mulitAddToCartJson));
        }
        /// <summary>
        /// 移除购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult RemoveFromCart()
        {
            string removeFromCartJson = GetInputJson();
            return Json(service.RemoveFromCart(removeFromCartJson));
        }
        #region 异步提交所有订单
        #region 测试
        //订单测试数据
        public string TestSubmitOrder()
        {
            
            var tmpParam = new
            {
                stock = new { CustomerID = 96, IsFancy = 0, InventoryIDs = "2615339", OrderType = 2, Remarks = "test" },
                parcel = new { CustomerID = "96", CartType = 1, ParcelIDs = "1187", Remarks = "单个直接购买" },
                ring = new { CustomerID = "96", RingIDs = "65822", OrderType = 2, IsStock = "定制", Remarks = "单个直接购买" },
                gem = new { CustomerID = "96", GemIDs = "1372", OrderType = "1", Remarks = "单个直接购买" },
                emerald = new { CustomerID = "96", EmeraldIDs = "2", OrderType = "1", Remarks = "单个直接购买" }
            };
            return JsonConvert.SerializeObject(tmpParam);
        }
        #endregion end测试
        [HttpPost]
        public string SubmitOrderList()
        {
            //var j = new { msgcode = true, msginfo = new { Successful = 0, Successful1 = 0, Failed = 1, Failed1 = 0 } };
            //var j = "{\"msgcode\":true,\"msginfo\":{\"Successful\":0,\"Successful1\":0,\"Failed\":1,\"Failed1\":0}}";
            //var a = JsonConvert.DeserializeObject<MvcWechat.Result>(j);
            tmpAllResult = new Dictionary<string, object>();
            SubmitOrderListAsync(); //异步同时提交到各自的接口
            Root root = JsonConvert.DeserializeObject<Root>(JsonConvert.SerializeObject(tmpAllResult)); //因为stock的msginfo也是一个对像所以用了一个类转换，及去掉async自动生成的属性
            return JsonConvert.SerializeObject(root);
            //return Json(_root, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 提交订单(微信购物车结算，多个产品一起提交)
        /// </summary>
        /// <returns></returns>
        public async Task SubmitOrderListAsync()
        {
            string submitOrderJson = GetInputJson();//TestSubmitOrder()
            var list = JsonConvert.DeserializeObject<Dictionary<string, object>>(submitOrderJson);
            if (list.ContainsKey("stock"))
            {
                var tmpStockResult = SubmitOrder(JsonConvert.SerializeObject(list["stock"]));
                tmpAllResult.Add("stock", tmpStockResult);
            } 
        }
        private Task<string> SubmitOrder(string requestJson)
        {
            return Task.Run(() => { return service.SubmitOrder(requestJson); });
        }
       
        #endregion
        //public string Test() {
        //    GetAllCartsList();
        //}
        #region 异步得到所有购物车
        /////////////////////////
        [HttpPost]
        public JsonResult GetAllCartsList()
        { 
            return Json(service.GetAllCartsList(GetParentKeyInputJson()));
        }
        /// <summary>
        ///  //异步加载所有购物车
        /// </summary>
        /// <returns></returns>
        public async Task GetAllCartsAsync(string getAllCartByParam)
        {
            //string getAllCartByParam = JsonConvert.SerializeObject(json); //GetInputJson();
            tmpAllResult.Add("stock", GetCartInfos(getAllCartByParam)); 
        }
        private Task<string> GetCartInfos(string requestJson)
        {
            return Task.Run(() => { return service.GetCartInfos(requestJson); });
        }
           
        #endregion
        #region 异步提交所有订单
        #region 测试
        //订单测试数据
        public string TestDeleteAllProductCart()
        {
            var tmpParam = new
            {
                //stock = new { CustomerID = 96, InventoryID = "2615339" },
                //parcel = new { CustomerID = "96", ParcelID = "1187" },
                ring = new { CustomerID = "96", RingIDs =new int[2]{67469,67468} },
                //gem = new { CustomerID = "96", GemID = "1372" },
                //emerald = new { CustomerID = "96", EmeraldID = "2" },
                //prime_golds = new { CustomerID = "96", PrimeGoldID = "2" }
            };
            return JsonConvert.SerializeObject(tmpParam);
        }
        #endregion end测试
        [HttpPost]
        public string DeleteAllProductCart()
        {
            //var j = new { msgcode = true, msginfo = new { Successful = 0, Successful1 = 0, Failed = 1, Failed1 = 0 } };
            //var j = "{\"msgcode\":true,\"msginfo\":{\"Successful\":0,\"Successful1\":0,\"Failed\":1,\"Failed1\":0}}";
            //var a = JsonConvert.DeserializeObject<MvcWechat.Result>(j);
            tmpAllResult = new Dictionary<string, object>();
            DeleteAllProductCartAsync(); //异步同时提交到各自的接口
            Root root = JsonConvert.DeserializeObject<Root>(JsonConvert.SerializeObject(tmpAllResult)); //因为stock的msginfo也是一个对像所以用了一个类转换，及去掉async自动生成的属性
            var json = JsonConvert.SerializeObject(root, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore });
            return json;
            //return Json(_root, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 提交订单(微信购物车结算，多个产品一起提交)
        /// </summary>
        /// <returns></returns>
        public async Task DeleteAllProductCartAsync()
        {
            //test
            //string submitOrderJson = TestDeleteAllProductCart();
            string submitOrderJson = GetInputJson();//TestDeleteAllProductCart()
            var list = JsonConvert.DeserializeObject<Dictionary<string, object>>(submitOrderJson);
            if (list.ContainsKey("stock"))  //支持多个 删除 其它只支持一个
            {
                var tmpStockResult = RemoveFromCart(JsonConvert.SerializeObject(list["stock"]));
                tmpAllResult.Add("stock", tmpStockResult);
            }
             
        }
        private Task<string> RemoveFromCart(string requestJson)
        {
            return Task.Run(() => { return service.RemoveFromCart(requestJson); });
        }
       
        #endregion
        /////////////////////////
        #region 异步得到所有订单
        [HttpPost]  //, WeixinOAuthAuthorizeAttribute
        public JsonResult GetAllOrdersList()
        {
            //string requestJson = GetInputJson();
            //tmpAllResult = new Dictionary<string, object>();
            //GetAllOrdersAsync(requestJson); //异步同时提交到各自的接口
            //Root root = JsonConvert.DeserializeObject<Root>(JsonConvert.SerializeObject(tmpAllResult)); //因为stock的msginfo也是一个对像所以用了一个类转换，及去掉async自动生成的属性
            //return JsonConvert.SerializeObject(root).Replace("Data", "rows");

            return Json(service.GetAllOrdersList(GetInputJson()));
        }
        /// <summary>
        ///  //异步加载所有购物车
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task GetAllOrdersAsync(string getAllOrdersByParam)
        {
            //var json = new { CustomerID = 1261, PageSize = 200, PageIndex = 1, OrderStatus = -1 };
            //string getAllOrdersByParam = JsonConvert.SerializeObject(json); //GetInputJson();
            tmpAllResult.Add("stock", GetStockOrders(getAllOrdersByParam));  
        }
        private Task<string> GetStockOrders(string requestJson)
        {
            return Task.Run(() => { return service.GetOrders(requestJson); });
        }
        
        #endregion
   
        /// <summary>
        /// 获取全局销售汇率 11-10
        /// </summary>
        /// <returns></returns>
        public JsonResult GetRate()
        {
            return Json(service.GetRate(GetInputJson())); ;
        }
        /// <summary>
        /// 在线通知
        /// </summary>
        /// <returns></returns>
        public JsonResult GetNotice()
        {
            return Json(service.GetNotice(GetInputJson()), JsonRequestBehavior.AllowGet);
        }
        //////////////以下为Parcel方法/////////////////////
        
        /// <summary>
        /////加入购物车
        ///// </summary>
        ///// <param name="ringParam"></param>
        ///// <returns></returns>
        public JsonResult AddParcelsCart() { return Json(service.AddCart(GetInputJson())); }
        //
        
        //////////////////以下为Ring方法////////////////////////////////////
        //成品列表
        public JsonResult GetInlays()
        {
            return Json(service.GetInlays(GetInputJson()));
        }
        //成品单个
        public JsonResult GetInlay()
        {
            return Json(service.GetInlay(GetInputJson()));
        }
        /// <summary>
        /// 加入购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult AddRingsCart()
        {
            return Json(service.AddCart(GetInputJson())); ;
        }
        
        /// <summary>
        /// 单个订单
        /// </summary>
        /// <returns></returns>
        public JsonResult GetRingOrderInfo()
        {
            return Json(service.GetRingOrderInfo(GetInputJson())); ;
        }
        
        //public JsonResult AddGemsOrder()
        //{
        //    return Json(service.AddGemsOrder(GetInputJson()));
        //}
        public JsonResult AddGemsCart()
        {
            return Json(service.AddCart(GetInputJson()));
        }
        
        //public JsonResult AddEmeraldsOrder()
        //{
        //    return Json(service.AddEmeraldsOrder(GetInputJson())); ;
        //}
        public JsonResult AddEmeraldsCart()
        {
            return Json(service.AddCart(GetInputJson()));
        }
        #region 素金方法
        
        ///加入购物车
        public JsonResult AddPrimeGoldsCart() { return Json(service.AddCart(GetInputJson())); }
        /// 获取成品购物车业务列表
        
        #endregion
        public JsonResult DeleteReceivingAddress()
        {
            return Json(service.DeleteReceivingAddress(GetInputJson()));
        }
        public JsonResult EditReceivingAddress()
        {
            return Json(service.EditReceivingAddress(GetInputJson()));
        }
        public JsonResult GetReceivingAddress()
        {
            return Json(service.GetReceivingAddress(GetInputJson()));
        }
        public JsonResult AddReceivingAddress()
        {
            return Json(service.AddReceivingAddress(GetInputJson()));
        }
        public JsonResult GetMarketRate()
        {
            return Json(service.GetMarketRate(GetInputJson()));
        } 

        #region
        /// <summary>
        /// 提交订单
        /// </summary>
        /// <returns></returns>
        public JsonResult SubmitOrders()
        {
            return Json(service.SubmitOrders(GetParentKeyInputJson(),""));
        }
        /// <summary>
        /// 添加购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult AddCart()
        {
            string getCustomerInfoJson = GetInputJson();
            return Json(service.AddCart(getCustomerInfoJson));
        }
        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <returns></returns>
        public JsonResult DeleteCart()
        {
            return Json(service.DeleteCart(GetInputJson()));
        }
        /// <summary>
        /// 更新订单状态
        /// </summary>
        /// <returns></returns>
        public JsonResult UpdateProductsOrder()
        {
            return Json(service.UpdateProductsOrder(GetInputJson()));
        }
        /// <summary>
        /// 订单统计
        /// </summary>
        /// <returns></returns>
        public JsonResult OrderNumber()
        {
            return Json(service.OrderNumber(GetInputJson()));
        } 
        #endregion

     
        ///// <summary>
        ///// 客户资料
        ///// </summary>
        ///// <returns></returns>
        [HttpPost]
        public JsonResult GetCustomerInfo()
        {
            string getCustomerInfoJson = GetInputJson();
            return Json(service.GetCustomerInfo(getCustomerInfoJson));
        } 

        public int GetCustomerIdByOpenid(string openid)
        {
            Logger.Debug(this.GetType(), "Info path 3 GetCustomerIdByOpenid openid:" + openid);
            int cid = 0;
            if (System.Web.HttpContext.Current.Session["CustomerID"] != null && System.Web.HttpContext.Current.Session["CustomerID"].ToString()!="0")
            {
                Logger.Debug(this.GetType(), "is session customerId:" + System.Web.HttpContext.Current.Session["CustomerID"]);
                cid = Convert.ToInt32(System.Web.HttpContext.Current.Session["CustomerID"]);
            }
            else
            {
                cid= service.GetCustomerIdByOpenid(openid, CommonPage.getKey());
                Logger.Debug(this.GetType(), "is service.GetCustomerIdByOpenid(openid) customerId:" + cid);
                System.Web.HttpContext.Current.Session["CustomerID"] = cid;
            }
            return cid;
        }
        public string GetViewStyle()
        {
            //也可用字典 IDictionary dict = ConfigurationManager.GetSection("ViewStyle") as IDictionary;
            return (ConfigurationManager.GetSection("ViewStyle") as ViewStyle).Value;
        }
        [HttpPost]
        public string SetViewStyle()
        {
            string getCustomerInfoJson = GetInputJson();
            try
            {
                var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(getCustomerInfoJson);
                var styleVal = dict["SetStyleVal"];
                //Configuration config = WebConfigurationManager.OpenWebConfiguration(AppDomain.CurrentDomain.BaseDirectory + "Web.config" ); //Path.Combine(Server.MapPath("~"),"web.config")  //用这两种都会报此错：此处不允许使用相对虚拟路径
                //Configuration config = WebConfigurationManager.OpenWebConfiguration("~"); 
                //AppSettingsSection app = config.AppSettings;  //这种也可以使用，会把AppSettings 里面的注释去掉
                ////app.Settings.Add("ViewStyle", styleVal); //这种是添加
                //app.Settings["ViewStyle"].Value = styleVal; //修改
                //config.Save(ConfigurationSaveMode.Modified);
                Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
                ViewStyle viewStyle = config.GetSection("ViewStyle") as ViewStyle;
                viewStyle.Value = styleVal; 
                config.Save();
                return "修改成功";
            }
            catch (Exception ex)
            {
                Logger.Error(this.GetType(), ex.Message);
                return "修改失败，"+ex.Message;
            }
        }

        public ActionResult Encrypt(string key) {
            if (!string.IsNullOrEmpty(key))
            {
                if (key.Length < 24)
                {
                    key = key.PadRight(24, '0');
                }
                else if (key.Length>24){
                    key = key.Substring(0, 24);
                }
                var result = Des3.DES3Encrypt("wechat", key);
                return Content(result);
            }
            else {
                return Content(key);
            }
        }

        #region 查询所有商品库存
        /// <summary>
        /// 查询所有商品库存 TAG
        /// </summary>
        /// <param name="strParam"></param>
        /// <returns></returns> 
        public JsonResult GetAllProducts()
        {
            return JsonK.Json(service.GetAllProducts(GetInputJson()), JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}
